package models

import (
	"encoding/json"
	"strconv"
)

//WsMessage websocket传输消息体
type WsMessage struct {
	Action string `json:"action"`
	Data map[string]interface{} `json:"data"`
}

func (this *WsMessage) GetDataJson() string {
	v, _ := json.Marshal(this.Data)
	return string(v)
}

func (this *WsMessage) GetString(key string, def ...string) string {
	val := ""
	if this.Data[key] != nil {
		switch value := this.Data[key].(type) {
		case string:
			val = value
		case int64:
			val = strconv.FormatInt(value, 10)
		case float64:
			val = strconv.FormatFloat(value, 'f', -1, 64)
		}
	}
	if val == "" && len(def) > 0 {
		return def[0]
	}
	return val
}

func (this *WsMessage) GetInt(key string, def ...int) int {
	val := 0
	if this.Data[key] != nil {
		switch value := this.Data[key].(type) {
		case string:
			val,_ = strconv.Atoi(value)
		case int64:
			val = int(value)
		case float64:
			val = int(value)
		}
	}
	if val == 0 && len(def) > 0 {
		return def[0]
	}
	return val
}

func (this *WsMessage) GetFloat64(key string, def ...float64) float64 {
	val := float64(0)
	if this.Data[key] != nil {
		switch value := this.Data[key].(type) {
		case string:
			val,_ = strconv.ParseFloat(value, 64)
		case int64:
			val = float64(value)
		case float64:
			val = value
		}
	}
	if val == 0 && len(def) > 0 {
		return def[0]
	}
	return val
}